<template>
    <div class="table">
        <div class="divSearch">
            <!--搜索框-->
            <Row>
                <Col :lg="{span:5}" :md="{span:8}" :sm="{span:16}" :xs="{span:22}">
                    <label class="searchLabel">填报年度:</label>
                    <Select v-model="searchModel.FillInYear" placeholder="全部" :label-in-value="true" @on-change="getReportData()" class="searchInput">
                        <Option :value="item.DictText" v-for="item in CreateYearList" :key="item.DictValue">{{item.DictText}}</Option>
                    </Select>
                </Col>
                <Col :lg="{span:2}" :md="{span:2}" :sm="{span:2}" :xs="{span:2}">
                    <Button icon="ios-search" type="primary" @click="getReportData()" class="searchButton" v-show="isFull">查询</Button>
                </Col>
                <Col :lg="{span:2}" :md="{span:2}" :sm="{span:3}" :xs="{span:2}" style="float:right"  >
                    <Button v-show="ReportStatus >1" icon="ios-download" type="primary" @click="ExcelDown()" class="searchButton">数据导出</Button>
                </Col> 
                <Col :lg="{span:2}" :md="{span:2}" :sm="{span:2}" :xs="{span:2}" style="float:right" v-show="ReportStatus <3&&isFull">
                    <Upload :on-success="handleSuccess" :action="GetPostUrl()" >
                        <Button type="primary" icon="ios-cloud-upload-outline" class="searchButton">数据导入</Button>
                    </Upload>
                </Col>
                <Col :lg="{span:2}" :md="{span:2}" :sm="{span:2}" :xs="{span:2}"  style="float:right">
                    <Button icon="ios-cloud-download" type="primary" @click="TmpDown()" class="searchButton">模板下载</Button>
                </Col>
            </Row>
        </div>
        <Row>
            <Col>
                <div v-if="isFull">
                    <table class="reportTable">
                        <caption>
                            <label style="float:left">(七){{searchModel.FillInYear}}蔬菜冷库调查表(全面统计)</label>
                            <label style="float:right">当前状态:
                                <span v-if="ReportStatus==0" class="Error">退回重报</span> 
                                <span v-else-if="ReportStatus==1" class="NoReport">未填写</span>
                                <span v-else-if="ReportStatus==2" class="AlreadyReport">已填写</span>
                                <span v-else-if="ReportStatus==3" class="UpReport">已上报</span>
                                <span v-else-if="ReportStatus==4" class="Success">审核通过</span>               
                                <span v-else class="NoReport">无需填报</span>               
                            </label>
                            <br>
                            <label style="float:left">
                                <!-- <Button icon="plus" type="success"  @click="addItem" :disabled="ReportStatus < 3 && BtnSaveStatus ? false:true">新增</Button> -->
                                <Button icon="plus" type="success"  @click="addItem" >新增</Button>
                            </label>
                        </caption>
                        <thead>
                            <tr>
                                <td>序号</td>
                                <td>冷库单位名称</td>
                                <td>冷库组织性质</td>
                                <td>冷库数量(座)</td>
                                <td>冷库库容(立方米)</td>
                                <td>备注</td>                            
                                <td>操作</td>                            
                            </tr>
                        </thead>
                        <tr v-for="(dataitem,index) in datalist" :key="dataitem.Id" > 
                            <td>{{index+1}}</td>           
                            <td> 
                                <Input style="text-align:center" v-model="dataitem.UnitName" placeholder="请输入冷库单位名称"></Input>
                            </td>
                            <td>                            
                                <!-- <Input v-model="dataitem.OrganizeType" placeholder="请输入育苗组织性质"></Input> -->
                                <Select v-model="dataitem.OrganizeType" placeholder="请选择冷库组织性质" >
                                    <Option :value="item.DictValue" v-for="item in UnitTypeList" :key="item.DictValue">{{item.DictText}}</Option>
                                </Select>
                            </td>
                            <td>                        
                                <Input v-model="dataitem.ColdStorageNum" placeholder="请输入"></Input>
                            </td>                                                     
                            <td>
                                <Input v-model="dataitem.ColdStorageCapacity" placeholder="请输入年育苗销售株树"></Input>
                            </td>
                            <td>
                                <Input v-model="dataitem.Remark" placeholder="请输入150字以下"></Input>
                            </td>
                            <td>
                                <Button type="ghost" size="small" icon="ios-trash-outline" style="color:#FF0000" @click="delOp(dataitem)" :disabled="ReportStatus < 3 && BtnSaveStatus ? false:true"></Button>
                            </td>
                        </tr>
                        
                    </table>
                    <div class="divButton">
                        <Button type="primary" @click="save()" :disabled="ReportStatus < 3 && BtnSaveStatus ? false:true">保存</Button>
                        <Button type="primary" @click="DataUp()" :disabled="ReportStatus == 2 ? false:true">上报</Button>
                    </div>
                </div>
                <div class="FIllTip" v-else>温馨提示:本时段不在系统报表填报时间内，请耐心等待。</div>
                 <Alert class="alert" banner type="error">
                   <p>填报时间：每年1月10日</p>
                   <p>1.全省范围内从乡（镇）起，逐级全面统计，由县级填报经州（市）审核后上报。</p>
                    <span slot="desc"></span>
                </Alert>
            </Col>

        </Row>
        
    </div>
</template>
<script>
    export default {
        data() {
            const validateData=(rule, value, callback) => {
                var temp=/^[0-9]\d*(\.\d+)?$/;//验证规则
                if(value!=null&&value!="")
                {
                    if(temp.test(value)==false)
                    {
                        callback(new Error('必须是大于0的数字'));
                    }
                    else{
                        callback();  
                    }
                }else{
                    callback();
                }
            };
            return {
                self: this,
                CreateYearList: this.GetGroupDict("ReportYear"), //周期
                UnitTypeList: this.GetGroupDict("UnitType"), //组织性质
                CurrentYear: this.GetCurrentYear(),//当前年度
                ReportStatus:'',
                isFull:false,
                ReportId:'',
                BtnSaveStatus: false,//保存按钮开关
                //查询模型：根据需求删除不不要查询条件
                //蔬菜生产情况表代码
                searchModel: {
                    Id: '0',
                    ReportCode: 'ColdStorage',
                    FillInYear: '',
                    TimesType: '',
                    AreaCode: this.GetlocaStorage("VegUserInfo").AreaCode,
                    PageNumber: 1,
                    PageSize: 20,
                    Status: '',
                    Opinion: ''
                },
                // DataModel:{//数据表代码
                //     Id:'',
                //     ReportId:'',
                //     UnitName:'',//单位名称
                //     OrganizeType:'',//组织类型
                //     GrowSeedleArea:'',//育苗面积
                //     GrowSeedleNum:'',//年育苗销售株树（含自用）（万株）
                //     ReportStatus:'',                    
                // },
                datalist:[],
                ruleModel:{
                    GrowSeedleArea:[{ validator: validateData, trigger: 'blur' }],
                    GrowSeedleNum: [{ validator: validateData, trigger: 'blur' }]//年育苗销售株树（含自用）（万株）
                },
                ctx: this, //table数据上下文
                clientHeight: window.innerHeight - 270, //表格默认高度
            }
        },
        mounted() {
            //table高度计算方法
            const that = this;
            window.onresize = () => {
                return (() => {
                    that.clientHeight = window.innerHeight - 270;
                })()
            };
        },
        methods: {
            addItem(){
                var model = { //编辑模型
                    Id:0,
                    ReportId:'',
                    UnitName:'',//单位名称
                    OrganizeType:'',//组织类型
                    ColdStorageNum:'',//育苗面积
                    ColdStorageCapacity:'',//年育苗销售株树（含自用）（万株）
                    ReportStatus:'', 
                };
                model.ReportId = this.ReportId;
                model.Id = this.datalist.length + 1;
                this.datalist.push(model);
            },
            delOp(m) {
                for (var i = 0; i < this.datalist.length; i++) {
                    if (this.datalist[i].Id == m.Id) {
                        if(this.deleteData(m.Id))
                        {
                            this.datalist.splice(i, 1);
                            self.$Notice.success({
                                title: '数据移除成功！',
                                desc: false
                            });
                        }
                        else{
                            this.datalist.splice(i, 1);
                        }
                    }
                }
            },
            deleteData(ID){
                var self=this;
                self.$http.delete("VegColdStorage",{params: {id: ID}}).then(
                    function(res){
                        if(res.data.status) {//删除成功
                            self.getReportData();
                            return true;
                        }
                        else{//删除失败
                            return false;
                        }
                    }
                )
            },
            Import:function(ReportId,ReportCode){//数据导入
                var self=this;
                self.postExcel.post().then(function(res){
                    if(res.data.status===1){
                          self.$Notice.success({
                            title: res.data.message,
                            desc: false
                        });
                    }
                    else{
                          self.$Notice.success({
                            title: res.data.message,
                            desc: false
                        });
                    }
                });
            },
            TmpDown:function(){//模板下载
                window.open(this.$http.defaults.baseURL + "Report/GetTemplateData?ReportCode=" + this.searchModel.ReportCode);
            },
            getReportData() {
                var self = this;
                var user = this.GetlocaStorage("VegUserInfo");
                this.searchModel.AreaCode = user.AreaCode;
                if (self.searchModel.FillInYear != null && self.searchModel.FillInYear != '') {
                    self.searchModel.FillInYear = self.searchModel.FillInYear;
                    self.isFull= self.IsFillForTableYear(parseInt(self.searchModel.FillInYear));
                } else {
                    self.isFull= self.IsFillForTableYear(self.CurrentYear);                
                    self.searchModel.FillInYear = self.CurrentYear + '年'; //填报年度-----数据字典值
                }
                self.$http.post('Report/PostPageList', this.searchModel).then(function (res) {
                    if (res.data.status === 1) {
                        if (res.data.rows.length > 0) {
                            self.ReportId = res.data.rows[0].Id;
                            self.ReportStatus = res.data.rows[0].Status;
                            self.BtnSaveStatus = true;
                        } else {
                            self.ReportId = '';
                            self.ReportStatus = '';
                            self.BtnSaveStatus = false;
                        }
                        self.getPageData(self.ReportId);
                    } else {
                    self.$Modal.error({
                        title: '提示信息',
                        content: res.data.message
                    });
                    }
                });
            },
            //获取this.datas: {},//table数据对象
            getPageData(ReportId) {
                var self = this;
                var reportCode = self.searchModel.ReportCode;
                this.$http.get("Report", {
                    params: {
                    id: ReportId,
                    reportCode: reportCode
                    }
                }).then( //获取数据编辑项的值
                    function (res) {
                        switch (res.data.list.status) {
                            case 1:
                                self.ReportId=ReportId;
                                self.datalist = res.data.list.model;
                                break;
                            case 0:
                                self.$Modal.error({
                                    title: "提示信息",
                                    content: "数据加载失败!!!"
                                });
                                break;
                            case -1:
                                self.$Modal.error({
                                    title: "提示信息",
                                    content: "数据加载失败!!!"
                                });
                                break;
                        }
                });
            },
            // //保存方法
            save() {
                var self = this;
                this.$http.post('VegColdStorage', self.datalist).then(
                    function (res) {
                    if (res.data.status == 1) {
                        self.getReportData(); //读取分页数据
                        //self.datalist = [];
                        self.$Notice.success({
                        title: '保存成功！',
                        desc: false
                        });
                    } else {
                        self.$Modal.warning({
                        title: "提示信息",
                        content: "更新失败,请与管理员联系!"
                        });
                    }
                });
            },
            // 数据上报
            DataUp: function() {
                var self = this;
                var model = new Object();
                model.Id = self.ReportId;
                model.Status = 3;
                model.Opinion = '';
                self.$Modal.confirm({
                    title: '提示信息',
                    content: '<p>数据上报后，不能再更改，是否继续上报？</p>',
                    onOk: () => {
                        self.$http.post('Report/PostUpStatus', model).then(function(res) {
                            if (res.data.status === 1) {
                                self.$Notice.success({
                                    title: '数据上报成功',
                                    desc: false
                                });
                                self.getReportData(); //读取分页数据
                            } else {
                                self.$Notice.error({
                                    title: '数据上报失败',
                                    desc: res.data.messages
                                });
                            }
                        });
                    },
                    onCancel: () => {}
                });
            },
             //导出
            ExcelDown: function () {
                var self = this;
                var model = new Object();
                model.ReportCode = self.searchModel.ReportCode;
                if (self.searchModel.FillInYear != null && self.searchModel.FillInYear != '') {
                    model.FillInYear = self.searchModel.FillInYear;
                } else {
                    model.FillInYear = self.CurrentYear + '年';//填报年度-----数据字典值
                    self.searchModel.FillInYear = self.CurrentYear + '年';
                }
                model.AreaCode = self.searchModel.AreaCode;
                window.open(this.$http.defaults.baseURL + "VegColdStorage/GetExcelData?ReportCode=" + model.ReportCode + "&&FillInYear=" + model.FillInYear + "&&AreaCode=" + model.AreaCode);
            },
            //导入
            GetPostUrl() {
                var url = this.$http.defaults.baseURL + "Report/PostImportData?ReportCode=" + this.searchModel.ReportCode + "&&AreaCode=" + this.searchModel.AreaCode + "&&FillInYear=" + this.searchModel.FillInYear;
                return url;
            },
            handleSuccess(res, file) {
                var self = this;
                self.getReportData();
                self.$Notice.success({
                    title: '数据导入成功！',
                    desc: false
                });
            },
        },
        //创建Vue页面方法
        created: function() {
            //创业Vue前调用获取this.datas: {},//table数据对象
            this.getReportData();
        },
        watch: {
            //需要监听的在此处新增监听对象
        }
    }
</script>